'use strict';

const Service = require('egg').Service;
const sequelize = require('sequelize')
const { Op } = require('sequelize').Sequelize;

class BookService extends Service {

    async add(request) {
        const { Book } = this.ctx.model;

        let book = {
            createDate: new Date(),
            createBy: this.ctx.state.user.id
        }
        book.isbn = request.isbn;
        book.name = request.name;
        book.coverImgUrl = request.coverImgUrl;
        book.type = request.type;
        book.author = request.author;
        book.publishingHouse = request.publishingHouse;
        book.description = request.description;
        book.price = request.price;
        book.position = request.position;
        book.recommended = 0;
        book.lended = 0;
        book.onSale = 1;

        const retBook = await Book.create(book);

        return {
            result: true
        }
    }

    async list(pageNo, pageSize) {
        const offset = pageSize * (pageNo - 1);
        const limit = pageSize;

        const { id, type, name, isbn, recommended,description,publishingHouse } = this.ctx.query;

        let sql = 'SELECT b.id, b.isbn, b.name, b.cover_img_url coverImgUrl, b.type, b.author, b.publishing_house publishingHouse, '
        sql += 'b.description, b.price, b.position, b.recommended,b.lended, b.on_sale onSale, b.create_date createDate FROM book b '
        sql += 'left join book_type t on b.type = t.id where';
        if (type) sql += ` t.type like '%${type}%' `;
        if (id) sql += ` ${type ? ' and ' : ''} b.id = ${id} `;
        if (name) sql += ` ${type ? ' and ' : ''} b.name like '%${name}%' `;
        if (isbn) sql += ` ${type ? ' and ' : ''} b.isbn like '%${isbn}%' `;
        if (recommended) sql += ` ${type ? ' and ' : ''} b.recommended = ${recommended}`;
        if (publishingHouse) sql += ` ${type ? ' and ' : ''} b.publishing_house like '%${publishingHouse}%'`;
        if (description) sql += ` ${type ? ' and ' : ''} b.description like '%${description}%'`;
        if (!type && !id && !name && !isbn && !recommended && !publishingHouse && !description) sql = sql.replace('where', '')
        sql+=" order by b.create_date desc"
        const books = await this.ctx.model.query(sql, { type: sequelize.QueryTypes.SELECT });

        let hasNextPage = pageNo * pageSize < books.length;

        let result = {
            totalCount: books.length,
            pageNo,
            pageSize,
            books: books.splice(offset, limit),
            hasNextPage,
        };

        return result;
    }

    async update(request) {
        const { Book } = this.ctx.model;
        let book = await Book.findOne({
            where: {
                id: request.id
            }
        });

        if (!book) {
            this.ctx.throw(404, '书籍不存在！')
        }
        book.isbn = request.isbn;
        book.name = request.name;
        book.coverImgUrl = request.coverImgUrl;
        book.type = request.type;
        book.author = request.author;
        book.publishingHouse = request.publishingHouse;
        book.description = request.description;
        book.price = request.price;
        book.position = request.position;
        book.recommended = request.recommended?1:0;
        book.lended = request.lended;
        book.onSale = request.onSale?1:0;
        book.updateDate = new Date();
        book.updateBy = this.ctx.state.user.id;
        await book.save();

        return {
            result: true
        };

    }

    async onSaleChange(id) {
        const { Book } = this.ctx.model;
        let book = await Book.findOne({
            where: {
                id
            }
        });

        if (!book) {
            this.ctx.throw(404, '书籍不存在！')
        }
        if(book.lended==1){
            this.ctx.throw(400, '书籍未归还！')
        }
        book.onSale = 0;
        book.updateDate = new Date();
        book.updateBy = this.ctx.state.user.id;
        await book.save();

        return {
            result: true
        };

    }

    async delete(id) {
        const { LendedInfo, Book } = this.ctx.model;
        let book = await Book.findOne({
            where: {
                id
            }
        });

        if (!book) {
            this.ctx.throw(404, '书籍不存在！')
        }

        const lendedInfo = await LendedInfo.findOne({
            where: {
                [Op.and]: {
                    userId: id,
                    actualReturnDate: {
                        [Op.is]: null,
                    }
                }
            }
        });

        if (lendedInfo) {
            this.ctx.throw(400, '当前图书未归还，删除失败！')
        }

        await Book.destroy({
            where: {
                id
            }
        });

        return {
            result: true
        };

    }
}
module.exports = BookService;
